package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录的过滤器
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
//urlPatterns,拦截哪些路径
//继承servlet中的Filter
public class loginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前的uri
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", request.getRequestURI());
        //定义不需要拦截的uri
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };


        boolean check=check(urls,requestURI);

        //不需要处理，放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            //放行
            //过滤链FilterChain
            //调用doFilter方法实际上是在告诉过滤链：“我已经完成了对这个请求的前置处理（如果有的话），
            // 现在请将请求传递给链中的下一个过滤器或最终的目标资源（如Servlet）。”
            filterChain.doFilter(request, response);
            return;
        }
        //管理端已经登录，放行
        if(request.getSession().getAttribute("employee")!=null) {
            log.info("用户已登录，用户ID为:{}",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            log.info("BaseContext中储存的id为{}",BaseContext.getCurrentId());

            Long id = Thread.currentThread().getId();
            log.info("线程id为:{}",id);

            filterChain.doFilter(request, response);
            return;
        }
        //手机端已经登录，放行
        if(request.getSession().getAttribute("user")!=null) {
            log.info("用户已登录，用户ID为:{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            log.info("BaseContext中储存的id为{}",BaseContext.getCurrentId());

            Long id = Thread.currentThread().getId();
            log.info("线程id为:{}",id);

            filterChain.doFilter(request, response);
            return;
        }
        //未登录，给前端返回未登录结果
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //
        return;


    }


    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match) {
                return true;
            }
        }
        return false;
    }

}

